package com.juyu.miliao.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.common.domain.QQInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class QQGetUserInfoUtil {
    private static final String QQurl = "https://graph.qq.com/user/get_user_info";
    //	private static final String oauth_consumer_key = "101498937"; // app的appid
    private static final String format = "json"; // 非必选，默认为json,为了展现方便，调试器选用json格式。
    private final static Logger logger = LoggerFactory.getLogger(QQGetUserInfoUtil.class);

    public static QQInfo doGet(String access_token, String openid, String appid) {
        String response = null;
        HttpURLConnection httpURLConnection = null;
        BufferedReader br = null;
        String QQLoginUrl = "";
        try {
            QQLoginUrl = QQurl + "?oauth_consumer_key=" + appid + "&" + "access_token=" + access_token
                    + "&" + "openid=" + openid + "&" + "format=" + format;
            URL url = new URL(QQLoginUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String readLine = null;
            StringBuffer sb = new StringBuffer();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            response = sb.toString();
        } catch (Exception e) {
            logger.error("第三方登录QQ调用错误：", e);
        } finally {
            httpURLConnection.disconnect();
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                logger.error("第三方登录QQ异常:", ex);

            }
        }
        ObjectMapper mapper = new ObjectMapper();
        QQInfo qqInfo = null;
        try {
            qqInfo = mapper.readValue(response.toString(), QQInfo.class);
        } catch (Exception e) {
            logger.error("第三方登录QQ异常:", e);
        }
        return qqInfo;
    }
}
